package com.gopay.scheduler.job;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import com.gopay.common.util.DateUtils;

public class JobTimeMananger {
	private Logger logger = LoggerFactory.getLogger(JobTimeMananger.class);
	public static JobTimeMananger instance = null;
	private ClassPathXmlApplicationContext context = null;
	private SchedulerFactoryBean schedFactory = null;
	private  Trigger trigger = null;
	private JobTimeMananger() {
		context = new ClassPathXmlApplicationContext("spring-config.xml","spring/spring-config-job.xml");
		schedFactory =(SchedulerFactoryBean) context.getBean("allStartQuertz");
	
	}
	//当前时间点
	private String time ="";
	public static JobTimeMananger getInstance() {
		if (instance == null) {
			instance = new JobTimeMananger();
			
		}
		return instance;
	}


	public List getTimes() {
		List list = new ArrayList();
		try {
			Properties props = new Properties();
			InputStream in = this.getClass().getResourceAsStream(
					"/conf/jobTimes.properties");
			props.load(in);
			in.close();
			Set keyValue = props.keySet();

			for (Iterator it = keyValue.iterator(); it.hasNext();) {
				String key = (String) it.next();
				String val = props.getProperty(key);
				list.add(Integer.parseInt(val));
			}
			return list;

		} catch (Exception e) {
			e.getStackTrace();
			return list;
		}

	}


	public String getNextTime() {
		List list = getTimes();
		Collections.sort(list);
		String now = DateUtils.now2string("HHmmss");
		int n = Integer.parseInt(now);
		boolean flag = false;
		for (Object object : list) {
			int m = (Integer) object;
			if (n < m) {
				n = m;
				flag = true;
				break;
			}

		}
		if(!flag){
			n = (Integer)list.get(0);
		}
		String message = n + "";
		// 不满6位补0
		if (message.length() < 6) {
			for (int i = 0; i < 6 - message.length(); i++) {
				message = "0" + message;
			}

		}
		return message;
	}

	private String format(String message) {

		String s = message.substring(4, 6);
		String m = message.substring(2, 4);
		String h = message.substring(0, 2);
		message = s + " " + m + " " + h + " * * ?";
		return message;
	}

	public String getTime() {
		String thisTime = time;
		try {
			TriggerKey triggerKey = new TriggerKey("earningsCalculateTrigger", Scheduler.DEFAULT_GROUP);
			trigger = schedFactory.getScheduler().getTrigger(triggerKey);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
		time = DateUtils.date2string(trigger.getNextFireTime(),"HHmmss");
		if(thisTime.equals("")){
			thisTime = time;
		}
		return thisTime;
	}
	
	
}
